<template>
  <view class="login-page">
    <!-- 返回首页按钮 -->
    <view class="back-home" @tap="navigateToHome">
      <text class="iconfont icon-back">&#xe697;</text>
      <text class="back-text">返回首页</text>
    </view>
    
    <!-- 登录卡片 -->
    <view class="login-container">
      <view class="login-card">
        <view class="logo">
          <image class="logo-img" src="../../image/logo.png" mode="aspectFit"></image>
          <text class="logo-text">康怡之家</text>
        </view>
        
        <view class="form-group">
          <view class="input-wrapper">
            <text class="iconfont icon-mobile"></text>
            <input 
              class="input" 
              type="number" 
              v-model="phone"
              placeholder="请输入手机号码"
              maxlength="11"
              :class="{ 'error': phoneError }"
              adjust-position="false"
              @focus="onFocus"
              @blur="onBlur"
            />
          </view>
          <text class="error-message" v-if="phoneError">请输入有效的手机号码</text>
        </view>
        
        <view class="form-group">
          <view class="input-wrapper">
            <text class="iconfont icon-lock"></text>
            <input 
              class="input" 
              :type="showPassword ? 'text' : 'password'"
              v-model="password"
              placeholder="请输入密码"
              :class="{ 'error': passwordError }"
              adjust-position="false"
              @focus="onFocus"
              @blur="onBlur"
            />
            <text class="password-toggle" @tap="togglePasswordVisibility">
              <view class="toggle-icon" :class="{ 'active': showPassword }">
                <text class="iconfont" v-if="showPassword">&#xe613;</text>
                <text class="iconfont" v-else>&#xe6c8;</text>
              </view>
            </text>
          </view>
          <text class="error-message" v-if="passwordError">密码不能为空</text>
        </view>
        
        <view class="login-btn-area">
          <button class="login-btn" @tap="handleLogin" :disabled="isLoading">登录</button>
        </view>
        
        <!-- 底部链接区域 -->
        <view class="bottom-links">
          <view class="link-item" @tap="handleForgotPassword">
            <text>忘记密码</text>
          </view>
          <view class="link-divider"></view>
          <view class="link-item" @tap="handleRegister">
            <text>注册账号</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { login } from '@/api/user'

// 定义页面参数
const props = defineProps({
  redirect: String
})

// 表单数据
const phone = ref('')
const password = ref('')
const phoneError = ref(false)
const passwordError = ref(false)
const isLoading = ref(false) // 加载状态
const showPassword = ref(false) // 控制密码显示/隐藏
const redirect = ref('') // 重定向地址

// 页面加载时处理参数
onMounted(() => {
  // 从路由参数获取重定向地址
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  if (currentPage && currentPage.$page && currentPage.$page.options) {
    if (currentPage.$page.options.redirect) {
      redirect.value = decodeURIComponent(currentPage.$page.options.redirect);
      console.log('重定向地址', redirect.value);
    }
  }
  
  // 如果有本地缓存的手机号和密码，自动填充
  const cachedPhone = uni.getStorageSync('cachedPhone');
  const cachedPassword = uni.getStorageSync('cachedPassword');
  if (cachedPhone) {
    phone.value = cachedPhone;
  }
  if (cachedPassword) {
    password.value = cachedPassword;
    // 清除缓存的密码，避免安全问题
    uni.removeStorageSync('cachedPassword');
  }
})

// 处理输入框焦点
const onFocus = () => {
  // 当输入框获得焦点时，延迟滚动页面
  setTimeout(() => {
    uni.pageScrollTo({
      scrollTop: 100,
      duration: 300
    })
  }, 300)
}

const onBlur = () => {
  // 当输入框失去焦点时，滚动回顶部
  setTimeout(() => {
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  }, 300)
}

// 切换密码显示/隐藏
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

// 登录处理
const handleLogin = () => {
  if (!phone.value.trim()) {
    uni.showToast({
      title: '请输入手机号码',
      icon: 'none'
    });
    return;
  }
  
  if (!password.value.trim()) {
    uni.showToast({
      title: '请输入密码',
      icon: 'none'
    });
    return;
  }
  
  // 显示登录中提示
  uni.showLoading({
    title: '登录中...'
  });
  
  // 调用登录API
  login({
    phone: phone.value,
    password: password.value
  })
    .then(res => {
      const { token, userInfo } = res.data;
      
      // 保存token到本地
      uni.setStorageSync('token', token);
      
      // 保存用户信息到本地
      if (userInfo) {
        uni.setStorageSync('userInfo', JSON.stringify(userInfo));
      }
      
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });
      
      // 如果有重定向地址，跳转回去
      setTimeout(() => {
        if (redirect.value) {
          if (redirect.value.indexOf('/pages/profile/index') > -1 || 
              redirect.value.indexOf('/pages/ai/index') > -1 || 
              redirect.value.indexOf('/pages/health/index') > -1) {
            // 如果是 tabBar 页面，使用 switchTab
            uni.switchTab({
              url: redirect.value
            });
          } else {
            // 如果不是 tabBar 页面，使用 redirectTo
            uni.redirectTo({
              url: redirect.value
            });
          }
        } else {
          // 否则跳转到首页
          uni.switchTab({
            url: '/pages/index/index'
          });
        }
      }, 1500);
    })
    .catch(err => {
      console.error('登录失败:', err);
      uni.showToast({
        title: '登录失败，请检查账号密码',
        icon: 'none'
      });
    })
    .finally(() => {
      uni.hideLoading();
    });
};

// 注册处理
const handleRegister = () => {
  uni.navigateTo({
    url: '/pages/register/index'
  })
}

// 忘记密码处理
const handleForgotPassword = () => {
  uni.navigateTo({
    url: '/pages/reset-password/index'
  })
}

// 返回首页处理
const navigateToHome = () => {
  uni.switchTab({
    url: '/pages/index/index'
  })
}
</script>

<style lang="scss">
page {
  height: 100%;
  background: linear-gradient(135deg, #f0f7f7 0%, #e9f0f5 100%);
}

.login-page {
  min-height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;
  
  // 返回首页按钮样式
  .back-home {
    position: fixed;
    top: 40px;
    left: 20px;
    z-index: 100;
    display: flex;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.9);
    padding: 8px 15px;
    border-radius: 20px;
    box-shadow: 0 2px 10px rgba(195, 227, 227, 0.2);
    
    .icon-back {
      font-size: 16px;
      margin-right: 4px;
      color: #2c7873;
    }
    
    .back-text {
      font-size: 14px;
      color: #2c7873;
    }
  }
  
  .login-container {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    
    .login-card {
      background: rgba(255, 255, 255, 0.95);
      padding: 30px 25px;
      border-radius: 20px;
      box-shadow: 0 8px 24px rgba(195, 227, 227, 0.2);
      width: 100%;
      max-width: 420px;
      position: relative;
      
      .logo {
        text-align: center;
        margin-bottom: 40px;
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .logo-img {
          width: 60px;
          height: 60px;
          margin-bottom: 12px;
        }
        
        .logo-text {
          color: #2c7873;
          font-size: 22px;
          font-weight: 600;
          line-height: 1.2;
        }
      }
      
      .form-group {
        margin-bottom: 20px;
        
        .label {
          display: block;
          margin-bottom: 8px;
          color: #2c7873;
          font-size: 15px;
          font-weight: 500;
        }
        
        .input-wrapper {
          position: relative;
          background: #fff;
          border-radius: 12px;
          border: 2px solid #c3e3e3;
          overflow: hidden;
          
          .iconfont {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #2c7873;
            font-size: 20px;
            z-index: 1;
          }
          
          .password-toggle {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            z-index: 10;
            
            .toggle-icon {
              display: flex;
              justify-content: center;
              align-items: center;
              width: 32px;
              height: 32px;
              border-radius: 50%;
              background-color: rgba(195, 227, 227, 0.2);
              transition: all 0.3s ease;
              
              .iconfont {
                position: static;
                font-size: 18px;
                color: #2c7873;
                transform: none;
                transition: all 0.3s ease;
              }
              
              &:active {
                background-color: rgba(195, 227, 227, 0.4);
                transform: scale(0.9);
              }
              
              &.active {
                background-color: rgba(195, 227, 227, 0.4);
                
                .iconfont {
                  color: #2c7873;
                }
              }
            }
          }
          
          .input {
            width: 100%;
            height: 48px;
            padding: 0 45px 0 40px;
            font-size: 16px;
            color: #2c7873;
            background: transparent;
            position: relative;
            z-index: 2;
            
            &:focus {
              border-color: #2c7873;
              box-shadow: 0 0 0 3px rgba(195, 227, 227, 0.3);
            }
          }
        }
        
        .input-wrapper.error {
          border-color: #ff5722;
        }
        
        .form-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 6px;
        }
        
        .error-message {
          color: #ff5722;
          font-size: 13px;
          flex: 1;
        }
        
        .forgot-password {
          text-align: right;
          
          text {
            color: #2c7873;
            font-size: 14px;
            font-weight: 500;
            
            &:active {
              opacity: 0.8;
            }
          }
        }
      }
      
      .login-btn-area {
        margin-bottom: 30px;
      }

      .login-btn {
        width: 100%;
        height: 48px;
        background: linear-gradient(135deg, #c3e3e3 0%, #2c7873 100%);
        border: none;
        border-radius: 12px;
        color: white;
        font-size: 16px;
        font-weight: 600;
        
        &:active {
          opacity: 0.9;
          transform: translateY(1px);
        }
      }

      .bottom-links {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 10px;
        
        .link-item {
          padding: 5px;
          
          text {
            color: #2c7873;
            font-size: 14px;
            font-weight: 500;
          }
          
          &:active {
            opacity: 0.7;
          }
        }
        
        .link-divider {
          width: 1px;
          height: 14px;
          background-color: #c3e3e3;
          margin: 0 15px;
        }
      }
    }
  }
}

// 响应式布局
@media screen and (max-width: 768px) {
  .login-page {
    padding: 16px;
    
    .login-container {
      .login-card {
        padding: 24px 20px;
      }
    }
  }
}
</style> 